// miniprogram/pages/chargeDetail/index.js
const { queryOrder } = require('../../utils/checkTimeout.js');
const API_KEY = getApp().globalData.API_KEY;
const deviceId = getApp().globalData.deviceId;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    marker:{},
    disabled:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLastPageData();
    this.getDeviceStatus(deviceId);
  },
  
  getLastPageData(){
    const that = this;
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('getSelectedMarker', function(res) {
      that.setData({  
        marker:res.data
      })
    })
  },

  makeAppointment(){
    const that = this;
    const userInfo = wx.getStorageSync('userInfo') || '';
    if (userInfo === '') {
      wx.showModal({
        cancelColor:'#ff0000',
        cancelText: '取消',
        title:'请登录',
        content:'该功能只有登录用户才能使用，是否去登录?',
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/my/index',
            });           
            //
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      wx.showModal({
        cancelColor: '#ff0000',
        cancelText: '取消',
        content:'是否预约？',
        success (res){
          if (res.confirm) {
            queryOrder();
            wx.navigateTo({
              url: `/pages/appointment/index?markerId=${ that.data.marker.id }`,
              success(result){
                result.eventChannel.emit('getMarker', { data: that.data.marker });
              }
            })
          }else if (res.cancel) {
            console.log('取消预约')
          }
        }
      })
    }
  },

  getDeviceStatus(device_id) {
    const that = this;
    //查看设备连接状态
    wx.request({
      url: `https://api.heclouds.com/devices/${device_id}`,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        "api-key": API_KEY
      },
      data: {},
      success(res) {
        console.log(res)
        if (res.data.data.online) {
          console.log("设备已经连接")         
          that.setData({ disabled:false });
          return true
        } else {
          console.log("设备还未连接");
          that.setData({ disabled:true })
          return false
        }
      },
      fail(res) {
        console.log("请求失败")
        deviceConnected = false
        return false
      }
    })
  },
  



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})